#include "adbworker.h"
#include <QProcess>
#include <QDebug>
ADBWorker::ADBWorker(QObject *parent) : QObject(parent)
{

}

void ADBWorker::ADBconnect(){
    // 构建ADB连接命令
    QStringList adbConnectArgs;
    adbConnectArgs << "connect" << m_radarip;
    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;
    // 执行ADB连接命令
    adbProcess.start("adb", adbConnectArgs);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    QString errorOutput = adbProcess.readAllStandardError();
    // 检查执行结果
    qDebug() << output;
    qDebug() << errorOutput;
    if(output.contains("connected")){
        //查询或设置硬件特征号
        emit sendADBmsg(3,"");
        ADBReadJson();

    }else{
        emit sendADBmsg(0,errorOutput);
    }
}

void ADBWorker::ADBdisconnect(){
    // 构建ADB连接命令
    QStringList adbConnectArgs;
    adbConnectArgs << "disconnect" << m_radarip;
    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;
    // 执行ADB连接命令
    adbProcess.start("adb", adbConnectArgs);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    QString errorOutput = adbProcess.readAllStandardError();
    // 检查执行结果
    qDebug() << output;
    qDebug() << errorOutput;
//    if(output.contains("disconnected")){
//        ui.textEdit->setTextColor(Qt::blue);
//        ui.textEdit->append("ADB断开成功");
//    }else{
//        ui.pushButton_5->setText("开始升级");
//        ui.textEdit->setTextColor(Qt::red);
//        ui.textEdit->append("ADB断开异常，升级终止" + output);
//        ui.textEdit->append("ADB断开异常原因" + errorOutput);
//    }
}

void ADBWorker::ADBreconnect(){

    // 构建ADB连接命令
    QStringList adbConnectArgs;
    adbConnectArgs << "disconnect";
    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;
    // 执行ADB连接命令
    adbProcess.start("adb", adbConnectArgs);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    QString errorOutput = adbProcess.readAllStandardError();
    // 检查执行结果
    qDebug() << output;
    qDebug() << errorOutput;
    if(output.contains("disconnected")){
        //emit sendADBmsg(1,"");
        ADBconnect();
    }else {
        emit sendADBmsg(2,errorOutput);
    }
}

void ADBWorker::ADBkillradar(){

    // 要搜索的关键字
    QString keyword = "radarTSMTC";

    // 构建ADB shell命令来查找包含关键字的进程ID
    QString adbShellPgrepCommand = QStringLiteral("adb shell pgrep -f %1").arg(keyword);

    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;

    // 执行ADB shell命令并读取输出
    adbProcess.start(adbShellPgrepCommand);
    adbProcess.waitForFinished();

    // 读取pgrep命令的输出，其中包含了符合条件的进程ID
    QString output = adbProcess.readAllStandardOutput();

    // 检查执行结果
    if (adbProcess.exitCode() == 0) {
        // 读取到的进程ID字符串
        QStringList pidList = output.split("\n", QString::SkipEmptyParts);

        // 杀死所有找到的进程
        for (const QString &pid : pidList) {
            QString adbShellKillCommand = QStringLiteral("adb shell kill -9 %1").arg(pid.trimmed());
            adbProcess.start(adbShellKillCommand);
            adbProcess.waitForFinished();
            qDebug() << "Process with PID" << pid << "terminated.";


        }
        emit sendADBmsg(6,"");
        ADBdeleterfile();
    } else {
        emit sendADBmsg(7,adbProcess.errorString());
        qDebug() << "Failed to query processes with keyword" << keyword << ":";
        qDebug() << adbProcess.errorString();

    }
}

void ADBWorker::ADBkillcamera(){
    // 要搜索的关键字
    QString keyword = "atk_yolov5";

    // 构建ADB shell命令来查找包含关键字的进程ID
    QString adbShellPgrepCommand = QStringLiteral("adb shell pgrep -f %1").arg(keyword);

    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;

    // 执行ADB shell命令并读取输出
    adbProcess.start(adbShellPgrepCommand);
    adbProcess.waitForFinished();

    // 读取pgrep命令的输出，其中包含了符合条件的进程ID
    QString output = adbProcess.readAllStandardOutput();

    // 检查执行结果
    if (adbProcess.exitCode() == 0) {
        // 读取到的进程ID字符串
        QStringList pidList = output.split("\n", QString::SkipEmptyParts);

        // 杀死所有找到的进程
        for (const QString &pid : pidList) {
            QString adbShellKillCommand = QStringLiteral("adb shell kill -9 %1").arg(pid.trimmed());
            adbProcess.start(adbShellKillCommand);
            adbProcess.waitForFinished();
            qDebug() << "Process with PID" << pid << "terminated.";
        }
        ADBsendcfile();
        //ADBdeletercfile();
    } else {

        qDebug() << "Failed to query processes with keyword" << keyword << ":";
        qDebug() << adbProcess.errorString();

    }
}

void ADBWorker::ADBsendrfile(){
    // 源文件路径和目标文件路径
    QString sourceFilePath = filepath[4];
    qDebug() << filepath[4];
    QFileInfo fileInfo(localFile[4]->fileName());
    QString filename(fileInfo.fileName());
    QString targetFilePath = "/demo/tsmtc/updata/tsm_radar/" + filename;
    qDebug() << targetFilePath;
    // 构建ADB push命令
    QString adbPushCommand = QStringLiteral("adb push %1 %2").arg(sourceFilePath).arg(targetFilePath);

    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;

    // 执行ADB push命令
    adbProcess.start(adbPushCommand);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    QString errorOutput = adbProcess.readAllStandardError();
    qDebug() << output;
    qDebug() << errorOutput;
    // 检查执行结果
    if (adbProcess.exitCode() == 0) {
        emit sendADBmsg(10,"");
        ADBchmodradar();
    } else {
        //ui.pushButton_5->setText("开始升级");
        emit sendADBmsg(11,errorOutput);
    }
}

void ADBWorker::ADBsendcfile(){
    // 源文件路径和目标文件路径
    QString sourceFilePath = filepath[0];
    qDebug() << filepath[0];
    QFileInfo fileInfo(localFile[0]->fileName());
    QString filename(fileInfo.fileName());
    QString targetFilePath = "/demo/tsmtc/updata/tsm_camera/" + filename;
    qDebug() << targetFilePath;
    // 构建ADB push命令
    QString adbPushCommand = QStringLiteral("adb push %1 %2").arg(sourceFilePath).arg(targetFilePath);

    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;

    // 执行ADB push命令
    adbProcess.start(adbPushCommand);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    QString errorOutput = adbProcess.readAllStandardError();
    qDebug() << output;
    qDebug() << errorOutput;
    // 检查执行结果
    if (adbProcess.exitCode() == 0) {
        emit sendADBmsg(10,"");
        ADBchmodcamera();
    } else {
        //ui.pushButton_5->setText("开始升级");
        emit sendADBmsg(11,errorOutput);
    }
}

void ADBWorker::ADBchmodcamera(){
    // 要更改权限的文件路径
    QFileInfo fileInfo(localFile[0]->fileName());
    QString filename(fileInfo.fileName());
    QString filePath = "/demo/tsmtc/updata/tsm_camera/" + filename;
    // 覦建立要更改的权限（例如，777表示读取、写入和执行权限）
    QString permission = "777";

    // 构建ADB shell命令来更改文件权限
    QString adbShellChmodCommand = QStringLiteral("adb shell chmod %1 %2").arg(permission).arg(filePath);

    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;

    // 执行ADB shell命令
    adbProcess.start(adbShellChmodCommand);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    QString errorOutput = adbProcess.readAllStandardError();
    qDebug() << output;
    qDebug() << errorOutput;
    // 检查执行结果
    if (adbProcess.exitCode() == 0) {
        qDebug() << "Permissions of file" << filePath << "changed successfully.";
        emit sendADBmsg(12,"");
        ADBreboot();

    } else {
        qDebug() << "Failed to change permissions of file" << filePath << ":";
        qDebug() << adbProcess.errorString();
        emit sendADBmsg(13,adbProcess.errorString());
    }
}

void ADBWorker::ADBdeletercfile(){
    // 构建ADB shell命令来查找并删除符合条件的文件
    QString adbShellCommand = "adb shell find /root -name atk_yolov5* -exec rm {} \\;";

    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;

    // 执行ADB shell命令
    adbProcess.start(adbShellCommand);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    QString errorOutput = adbProcess.readAllStandardError();
    qDebug() << output;
    qDebug() << errorOutput;
    // 检查执行结果
    if (adbProcess.exitCode() == 0) {
        qDebug() << "Files containing 'atk_yolov5' in root directory deleted successfully.";
        emit sendADBmsg(8,"");
        ADBsendcfile();
    } else {
        //ui.pushButton_5->setText("开始升级");
        qDebug() << "Failed to delete files containing 'atk_yolov5' in root directory:";
        qDebug() << adbProcess.errorString();
        emit sendADBmsg(9,adbProcess.errorString());
    }

}

void ADBWorker::ADBdeleterfile(){
    // 构建ADB shell命令来查找并删除符合条件的文件
    QString adbShellCommand = "adb shell find /root -name radarTSMTC* -exec rm {} \\;";

    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;

    // 执行ADB shell命令
    adbProcess.start(adbShellCommand);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    QString errorOutput = adbProcess.readAllStandardError();
    qDebug() << output;
    qDebug() << errorOutput;
    // 检查执行结果
    if (adbProcess.exitCode() == 0) {
        qDebug() << "Files containing 'radarTSMTC' in root directory deleted successfully.";
        emit sendADBmsg(8,"");
        ADBsendrfile();
    } else {
        //ui.pushButton_5->setText("开始升级");
        qDebug() << "Failed to delete files containing 'radarTSMTC' in root directory:";
        qDebug() << adbProcess.errorString();
        emit sendADBmsg(9,adbProcess.errorString());
    }

}

void ADBWorker::ADBchmodradar(){

    // 要更改权限的文件路径
    QFileInfo fileInfo(localFile[4]->fileName());
    QString filename(fileInfo.fileName());
    QString filePath = "/demo/tsmtc/updata/tsm_radar/" + filename;
    // 覦建立要更改的权限（例如，777表示读取、写入和执行权限）
    QString permission = "777";

    // 构建ADB shell命令来更改文件权限
    QString adbShellChmodCommand = QStringLiteral("adb shell chmod %1 %2").arg(permission).arg(filePath);

    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;

    // 执行ADB shell命令
    adbProcess.start(adbShellChmodCommand);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    QString errorOutput = adbProcess.readAllStandardError();
    qDebug() << output;
    qDebug() << errorOutput;
    // 检查执行结果
    if (adbProcess.exitCode() == 0) {
        qDebug() << "Permissions of file" << filePath << "changed successfully.";
        emit sendADBmsg(12,"");
        ADBreboot();

    } else {
        qDebug() << "Failed to change permissions of file" << filePath << ":";
        qDebug() << adbProcess.errorString();
        emit sendADBmsg(13,adbProcess.errorString());
    }

}

void ADBWorker::ADBreboot(){
    // 构建ADB shell命令来执行系统重启
    QString adbShellRebootCommand = QStringLiteral("adb shell reboot -f");

    // 创建一个QProcess对象来执行ADB命令
    QProcess adbProcess;

    // 执行ADB shell命令
    adbProcess.start(adbShellRebootCommand);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    QString errorOutput = adbProcess.readAllStandardError();
    qDebug() << output;
    qDebug() << errorOutput;
    // 检查执行结果
    if (adbProcess.exitCode() == 0) {
        qDebug() << "System reboot command executed successfully.";
        emit sendADBmsg(14,"");
    } else {
        //ui.pushButton_5->setText("开始升级");
        qDebug() << "Failed to execute system reboot command:";
        qDebug() << adbProcess.errorString();
        emit sendADBmsg(15,adbProcess.errorString());
    }

}




void ADBWorker::ADBReadJson(){
    // 这里是你的JSON文件路径，你需要替换成实际的路径
    QString jsonFilePath = "/demo/tsmtc/config/init_hardware_info.json";

    // 使用QProcess执行ADB命令
    QProcess adbProcess;
    adbProcess.start("adb", QStringList() << "shell" << "cat" << jsonFilePath);
    adbProcess.waitForFinished(-1); // 等待进程完成

    // 读取ADB输出
    QString adbOutput = adbProcess.readAllStandardOutput();

    // 解析JSON数据
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(adbOutput.toUtf8(), &parseError);

    // 检查解析是否成功
    if (parseError.error != QJsonParseError::NoError) {

        qDebug() << "Error parsing JSON:" << parseError.errorString();
        emit sendADBmsg(4,parseError.errorString());
        return;
    }

    // 如果JSON解析成功，输出JSON内容
    QJsonObject jsonObject = jsonDoc.object();
    //qDebug() << jsonObject;
    // 从JSON对象中获取名为 "hardware_info" 的子对象
    QJsonObject hardware = jsonObject.value("hardware_info").toObject();
    //qDebug() << hardware;
    QJsonArray  hardwareInfo = hardware.value("hard").toArray();
    //qDebug() << hardwareInfo;

    QByteArray hardArray;
    foreach (const QJsonValue &value, hardwareInfo) {
        hardArray.append(value.toInt());
    }
    qDebug() << "hardArray" << hardArray;
    // 输出 "hard" 数组的每个元素
    QString strData;
    strData = QString::fromLocal8Bit(hardArray.mid(0, 6).toHex().toUpper());
    emit sendADBmsg(5,strData);
    if(m_type){
        ADBkillradar();
    }else{
        ADBkillcamera();
    }

}

void ADBWorker::checkdevice(){
    QProcess adbProcess;
    // 执行ADB连接命令
    QStringList adbConnectArgs;
    adbConnectArgs << "devices";
    adbProcess.start("adb", adbConnectArgs);
    adbProcess.waitForFinished();
    QString output = adbProcess.readAllStandardOutput();
    ADBreconnect();
//    if(output.size() > 0){
//        qDebug() << output;

//    }else{
//        qDebug() << output;
//        ADBreconnect();
//    }
}
